package net.maergaiyun.component;

import net.maergaiyun.strategy.ShardingDBConfig;
import net.maergaiyun.strategy.ShardingTableConfig;
import net.maergaiyun.util.CommonUtil;
import org.springframework.stereotype.Component;

@Component
public class ShortLinkComponent {

    private static final String CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";


    public String createShortLinkCode(String param) {
        long murmurHash32 = CommonUtil.murmurHash32(param);
        String code = encodeToBase62(murmurHash32);
        String shortLinkCode = ShardingDBConfig.getRandomDBPrefix(code) + code + ShardingTableConfig.getRandomTableSuffix(code);
        return shortLinkCode;
    }

    private static String encodeToBase62(long num) {
        StringBuffer sb = new StringBuffer();
        do {
            int i = (int) (num % 62);
            sb.append(CHARS.charAt(i));
            num /= 62;
        } while (num > 0);
        String value = sb.reverse().toString();
        return value;
    }
}
